package com.heima.app.gateway.filter;

import com.heima.app.gateway.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求、响应对象
        ServerHttpResponse response = exchange.getResponse();
        ServerHttpRequest request = exchange.getRequest();
        //获取请求路径，判断请求的路径是否为登录，是就放行
        if (request.getURI().getPath().contains("/login_auth")){
            //放行
            return chain.filter(exchange);
        }
        //从请求头里获取用户token,判断是否为空，为空返回401
        String token = request.getHeaders().getFirst("token");
        if (StringUtils.isBlank(token)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();//请求到此结束，不再继续执行
        }
        //不为空对token进行校验，不通过就返回401
        Claims claims = AppJwtUtil.getClaimsBody(token);
        int status = AppJwtUtil.verifyToken(claims);
        if (status == 1 || status == 2){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();//请求到此结束，不再继续执行
        }
        //通过校验就放行
        return chain.filter(exchange);
    }
    //返回一个排序数字，数字越小，优先级越高
    //检验优先级最高 -1
    @Override
    public int getOrder() {
        return -1;
    }
}
